{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}积分管理 - 后台管理{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">积分管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <a href="{% url 'dashboard:points_records_management' %}" class="btn btn-sm btn-outline-primary me-2">
            <i class="bi bi-list-check"></i> 积分记录
        </a>
        <a href="{% url 'dashboard:rewards_management' %}" class="btn btn-sm btn-outline-success">
            <i class="bi bi-gift"></i> 奖品管理
        </a>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-primary h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            积分用户数</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_points_users }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-people fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-success h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            总积分</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_points }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-coin fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-info h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            可用积分</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_available_points }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-wallet2 fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-warning h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            平均积分</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ avg_points }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-graph-up fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 搜索和筛选 -->
<div class="card shadow mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <input type="text" name="search" class="form-control" placeholder="搜索用户名、昵称、邮箱..." value="{{ search_query }}">
            </div>
            <div class="col-md-2">
                <input type="number" name="points_min" class="form-control" placeholder="最小积分" value="{{ points_min }}">
            </div>
            <div class="col-md-2">
                <input type="number" name="points_max" class="form-control" placeholder="最大积分" value="{{ points_max }}">
            </div>
            <div class="col-md-4">
                <button type="submit" class="btn btn-primary me-2">
                    <i class="bi bi-search"></i> 搜索
                </button>
                <a href="{% url 'dashboard:points_management' %}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-clockwise"></i> 重置
                </a>
            </div>
        </form>
    </div>
</div>

<!-- 用户积分列表 -->
<div class="card shadow">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>用户</th>
                        <th>总积分</th>
                        <th>可用积分</th>
                        <th>已用积分</th>
                        <th>最后更新</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user_points in user_points_list %}
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="{{ user_points.user.get_avatar_url }}" alt="{{ user_points.user.username }}"
                                     class="rounded-circle me-2" width="32" height="32">
                                <div>
                                    <strong>{{ user_points.user.nickname|default:user_points.user.username }}</strong>
                                    <br>
                                    <small class="text-muted">@{{ user_points.user.username }}</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-primary">{{ user_points.total_points }}</span>
                        </td>
                        <td>
                            <span class="badge bg-success">{{ user_points.available_points }}</span>
                        </td>
                        <td>
                            <span class="badge bg-info">{{ user_points.used_points }}</span>
                        </td>
                        <td>{{ user_points.updated_at|date:"Y-m-d H:i" }}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary"
                                    onclick="showAdjustPointsModal({{ user_points.user.id }}, '{{ user_points.user.username }}')">
                                <i class="bi bi-pencil"></i> 调整积分
                            </button>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <i class="bi bi-coin text-muted display-4"></i>
                            <p class="text-muted mt-2">暂无积分数据</p>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 调整积分模态框 -->
<div class="modal fade" id="adjustPointsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">调整用户积分</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="adjustPointsForm">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="adjustUserId">
                    <div class="mb-3">
                        <label class="form-label">用户</label>
                        <input type="text" class="form-control" id="adjustUserName" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">调整类型</label>
                        <select name="adjustment_type" class="form-select" required>
                            <option value="add">增加积分</option>
                            <option value="deduct">扣除积分</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">积分数量</label>
                        <input type="number" name="points" class="form-control" min="1" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">调整说明</label>
                        <textarea name="description" class="form-control" rows="3" required
                                  placeholder="请填写积分调整的原因..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">确认调整</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function showAdjustPointsModal(userId, username) {
    document.getElementById('adjustUserId').value = userId;
    document.getElementById('adjustUserName').value = username;
    const modal = new bootstrap.Modal(document.getElementById('adjustPointsModal'));
    modal.show();
}

document.getElementById('adjustPointsForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const userId = formData.get('user_id');

    fetch(`/dashboard/points/users/${userId}/adjust/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(`积分调整成功`, 'success');
            bootstrap.Modal.getInstance(document.getElementById('adjustPointsModal')).hide();
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('网络错误，请重试', 'error');
    });
});

function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('main').insertBefore(alertDiv, document.querySelector('main').firstChild);
    
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
</script>
{% endblock %}